import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElButton,
  ElSpace,
  ElLink,
  ElMessage,
  ElMessageBox
} from 'element-plus'
// import { Plus } from '@element-plus/icons-vue'

import type { FormValuesType, InfoValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'

import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import AddGroup from './addGroup'
import styles from '../../index.module.scss'

// 单灯分组管理
export default defineComponent(function SingleLampGroup() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})

  const state = reactive({
    addVisible: false,
    type: 'add',
    record: {}
  })
  const userState = useVuexGetters('user', ['permission'])
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '分组名称',
      prop: 'name',
      minWidth: 180,
      align: 'center',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '排序',
      prop: 'sort',
      minWidth: 180,
      align: 'center',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 200,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('monitor_lampGroup_update') && (
            <ElLink type="primary" onClick={() => handleChangeAddGroupModal('update', row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('monitor_lampGroup_remove') && (
            <ElLink type="primary" onClick={() => handleRemove(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(() => {})

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  const handleChangeValueActionSearchList = () => {
    nextTick(proSaasTableRef.value!?.toSearch)
  }
  // 打开新增/编辑单灯弹窗
  const handleChangeAddGroupModal = (type: string, record?: InfoValuesType) => {
    state.type = type
    state.record = record || {}
    state.addVisible = !state.addVisible
    if (!state.addVisible) handleChangeValueActionSearchList()
  }

  const handleRemove = (record?: InfoValuesType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')

    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {<p class="delete-title">确认删除选中的分组？</p>}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('singleLamp/GroupDelete', { ids: params }).then(async (result) => {
          if (result?.success) ElMessage({ type: 'success', message: '操作成功' })
          proSaasTableRef.value!?.toSearch()
        })
      })
      .catch(() => {})
  }
  return () => (
    <ElCard>
      <ProSaasTable<FormValuesType>
        tableId="monitor_group_index"
        ref={proSaasTableRef}
        columns={columns}
        searchParams={formValues}
        hasSelection
        dispatchType="singleLamp/GroupList"
        searchFormProps={{
          model: formValues
        }}
        headerTitle={
          <>
            {userState.permission.value.has('monitor_lampGroup_add') && (
              <ElButton type="primary" onClick={() => handleChangeAddGroupModal('add')}>
                <AliIcon type="icon-xinzeng" />
                &nbsp; 新增
              </ElButton>
            )}
            {userState.permission.value.has('monitor_lampGroup_remove') && (
              <ElButton type="primary" onClick={() => handleRemove()}>
                <AliIcon type="icon-shanchu" />
                &nbsp; 批量删除
              </ElButton>
            )}
          </>
        }
        searchformResponsiveCol={[
          <ElFormItem key="name" prop="name" label="">
            <ElInput
              v-model={formValues.name}
              placeholder="分组名称"
              clearable
              onKeydown={handleKeyDownEnterSubmitForm}
              onClear={clearSearchTable}
            />
          </ElFormItem>
        ]}
      />
      {state.addVisible && (
        <AddGroup
          visible={state.addVisible}
          cancel={handleChangeAddGroupModal}
          type={state.type}
          record={state?.record}
        />
      )}
    </ElCard>
  )
})
